<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Products_model extends CI_Model {
    public function __construct() {
        parent::__construct();
        $this->load->database();
    }
    public function getAll() {
        $query = $this->db->query("
            SELECT *, left(product_details, 190) AS det_less FROM tb_products
            WHERE product_barangay_id_fk = " .
            $this->session->userdata('barangay_id') .
            " ORDER BY product_id_pk DESC
        ");
        return $query->result();
    }
    public function topProducts() {
        if($this->session->userdata('barangay_id') != '' || $this->session->userdata('barangay_id') != null) {
            $query = $this->db->query("
                SELECT product_id_pk AS product_id, product_name
                    FROM tb_products
                    WHERE product_barangay_id_fk = "
                    . $this->session->userdata('barangay_id') ."
                    LIMIT 8
            ");
            return $query->result();
        } else {
            return;
        }
    }
    public function insertProducts() {
        $query = $this->db->query("
            INSERT INTO tb_products
            VALUES(NULL, "
                .$this->session->userdata('barangay_id').", "
                .$this->session->userdata('user_id').", '"
                .$this->input->post('l_name')."', '"
                .$this->input->post('l_det')."', "
                ."NULL, SYSDATE())
        ");
        return $this->db->insert_id();
        //return $query;
    }
    public function getProductId($e=0) {
        //$query = $this->db->getwhere('tb_products', array('product_id_pk'=>$e));
        $query = $this->db->query("
            SELECT * FROM tb_products
            WHERE product_id_pk="
            .$e." AND product_barangay_id_fk="
            .$this->session->userdata('barangay_id')
            ." LIMIT 1
        ");
        //return $query->result();
        return $query->row_array();
    }
    public function deleteProducts($e=0) {
        $query = $this->db->query("
            DELETE FROM tb_products
            WHERE product_id_pk="
            .$e." AND product_barangay_id_fk="
            .$this->session->userdata('barangay_id')."
        ");
        return $query;
    }
    public function updateProducts() {
        $query = $this->db->query("
            UPDATE  tb_products SET product_name =  '"
            .$this->input->post('p_name')."',
            product_address =  '"
            .$this->input->post('p_det')."'
            WHERE product_id_pk ="
            .$this->input->post('p_id')." LIMIT 1 ;
        ");
        return 'ok';
    }
}